package com.panda.order.guanjiapo.api;

import com.alibaba.fastjson.JSONObject;
import com.panda.order.guanjiapo.Config;
import com.panda.order.guanjiapo.utils.AESCoder;
import com.panda.order.guanjiapo.utils.HttpRequest;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class GetTokenApi {


    public String DoGetToken(String authCode) throws Exception
    {
        //	String code = GetAuthCode(param);

        //��ȡp����
        JSONObject obj = new JSONObject();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//���Է�����޸����ڸ�ʽ
        Date now = new Date();
        String time = dateFormat.format(now);
        obj.put("TimeStamp", time);
        obj.put("GrantType", "auth_token");
        obj.put("AuthParam", authCode);
        String jsonParam = obj.toString();
        AESCoder coder = new AESCoder();
        String p = coder.encrypt(jsonParam, Config.app_secret);

        //��ȡsign
        JSONObject signObj = new JSONObject(true);
        signObj.put("appkey", Config.appkey);
        signObj.put("p", p);
        signObj.put("signkey", Config.sign_key);
        String sign = coder.SHA256(signObj.toString());

        //��Ȩ��ȡ
        Map<String, String> map = new HashMap<String, String>();
        map.put("appkey",Config.appkey);
        map.put("p",  URLEncoder.encode(p, "utf-8"));
        map.put("sign",sign);
        String postString = "";
        for (String in : map.keySet()) {
            postString += in + "=" +map.get(in) +"&";
        }
        postString = postString.substring(0, postString.length() - 1);
        String ret =  HttpRequest.sendPost(Config.get_token_url, postString);

        // 回传参数解析
        JSONObject jsonObject=JSONObject.parseObject(ret);
        String resp = jsonObject.getJSONObject("response").get("response").toString();
        String tokenStr = coder.decrypt(resp,  Config.app_secret);
        JSONObject tokenOnj=JSONObject.parseObject(tokenStr);

        return tokenOnj.get("auth_token").toString();
    }

    public String GetAuthCode(String param) throws Exception
    {
        String AuthCode = "";
        String[] params = param.trim().split("&");
        for(int i = 0; i < params.length; i++){
            if(params[i].toLowerCase().indexOf("auth_code") >= 0 && params[i].toLowerCase().indexOf("=") >= 0)
            {
                AuthCode = params[i].substring(params[i].toLowerCase().indexOf("="));
                break;
            }
        }
        if(AuthCode != "" && AuthCode.length() > 1)
        {
            AuthCode = AuthCode.substring(1);
        }
        else
        {
            throw new Exception("GJP-获取CODE失败");
        }
        return AuthCode;
    }

}


